package secure;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * ClassName: Bank
 * Package: secure
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-13
 * Time: 14:34
 */

//银行
public class Bank {

    //账户
    private static int account = 0;
    private static Object obj = new Object();

    //有两个储户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额
    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this + "甲");
                synchronized (obj) {
                    for (int i = 0; i < 3; i++) {
                        account += 1000;
                        System.out.println("甲: 余额存款为: " + account);
                    }
                }
            }

        }).start();

        //正常演示就是正确的问题还没暴露出来 但是 设置等待时间之后就是错误的
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //this是指当前对象 但是现在不唯一
                System.out.println(this + "乙");
                synchronized (obj) {
                    for (int i = 0; i < 3; i++) {
                        account += 1000;
                        System.out.println("乙: 余额存款为: " + account);
                    }
                }
            }
        }).start();


    }

}
